package com.offcn.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.offcn.bean.*;
import com.offcn.mapper.BlogMapper;
import com.offcn.mapper.BtypeMapper;
import com.offcn.mapper.EvaluateMapper;
import com.offcn.mapper.UserMapper;
import com.offcn.service.BlogService;
import com.offcn.utils.OAResult;
import com.offcn.utils.PageView;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    @Resource
    private BlogMapper blogMapper;
    @Resource
    private BtypeMapper btypeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private EvaluateMapper evaluateMapper;

    public PageView<Blog> getAllBlogs(int currentPage, Integer pageSize) {

        PageHelper.startPage(currentPage,pageSize);
        BlogExample blogExample=new BlogExample();
        List<Blog> blogList = blogMapper.selectByExample(blogExample);
        for (Blog blog : blogList) {
            Btype btype = btypeMapper.selectByPrimaryKey(blog.getTypeFk());
            User user = userMapper.selectByPrimaryKey(blog.getuFk());
            blog.setBtype(btype);
            blog.setUser(user);
        }
        PageInfo<Blog> pageInfo = new PageInfo<Blog>(blogList);
        PageView<Blog> pageView = new PageView<Blog>(currentPage,pageSize);
        pageView.setTotalrecords(pageInfo.getTotal());
        pageView.setRecords(pageInfo.getList());

        return pageView;
    }

    public Blog blogDetailById(int bid) {

        Blog blog = blogMapper.selectByPrimaryKey(bid);
        User user = userMapper.selectByPrimaryKey(blog.getuFk());
        blog.setUser(user);
        return blog;

    }

    public OAResult deleteBlog(int bid) {
        Blog blog = blogMapper.selectByPrimaryKey(bid);
        evaluateMapper.deleteByPrimaryKey(blog.getuFk());
        int rows = blogMapper.deleteByPrimaryKey(bid);
        if (rows==1){
            return OAResult.ok(200,"删除成功");
        }
        return OAResult.ok(400,"删除失败");

    }

    public OAResult saveBlog(Blog blog, HttpSession session) {
        User user = (User) session.getAttribute("activeUser");
        if (user!=null){
            blog.setuFk(user.getUid());
        }
        blog.setDate(new Date());
        int rows = blogMapper.insert(blog);
        if (rows==1){
            return OAResult.ok(200,"添加成功");
        }
        return OAResult.ok(400,"添加失败");

    }
}
